package org.idea.mq.framework.rocketmq.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.idea.mq.framework.rocketmq.common.FastJsonSerializer;
import org.idea.mq.framework.rocketmq.common.MqMsgSerializer;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;

/**
 * @Author linhao
 * @Date created in 5:03 下午 2022/4/20
 */
public class MqConsumerPushApplication {

    public static final String NAME_SERVER = "localhost:9876";
    public static MqMsgSerializer mqMsgSerializer = new FastJsonSerializer();

    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer("push-consumer-application");
        defaultMQPushConsumer.setNamesrvAddr(NAME_SERVER);
        defaultMQPushConsumer.subscribe("push-topic", "*");
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    long timeStamp = msg.getStoreTimestamp();
                    LocalDateTime localDateTime = new Date(timeStamp).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
                    System.out.println("broker存储时间:" + localDateTime + " " + new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        defaultMQPushConsumer.start();

    }
}
